package cn.seqdata.cxf.interceptor;

import java.util.List;

import javax.ws.rs.core.Response;

import org.apache.cxf.interceptor.AbstractOutDatabindingInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.jaxrs.interceptor.JAXRSOutInterceptor;
import org.apache.cxf.jaxrs.utils.JAXRSUtils;
import org.apache.cxf.message.Message;
import org.apache.cxf.message.MessageContentsList;
import org.apache.cxf.phase.Phase;

import cn.seqdata.cxf.wrapper.WrapperBean;
import cn.seqdata.cxf.wrapper.WrapperFault;

public class WrappedFaultOutInterceptor extends AbstractOutDatabindingInterceptor {

	public WrappedFaultOutInterceptor() {
		super(Phase.MARSHAL);
	}

	@Override
	public void handleMessage(Message message) throws Fault {
		final Fault f = (Fault) message.getContent(Exception.class);
		Response r = JAXRSUtils.convertFaultToResponse(f.getCause(), message);

		if (null != r) {
			// r不为null，属于 WebApplicationException，走正常处理逻辑
			JAXRSUtils.setMessageContentType(message, r);
			message.setContent(List.class, new MessageContentsList(r));

			// 禁止后续 JAXRSDefaultFaultOutInterceptor 执行
			message.getExchange()
				.put(JAXRSUtils.SECOND_JAXRS_EXCEPTION, true);
		} else {
			// 将异常包装并输出
			// TODO: !!!jrxian!!! 输出问题，出现不能解析的json
			message.removeContent(Exception.class);
			WrapperBean wrapper = new WrapperFault(f);
			message.setContent(List.class, new MessageContentsList(wrapper));
		}

		// 转 JAXRSOutInterceptor 输出逻辑
		new JAXRSOutInterceptor().handleMessage(message);
	}
}
